package com.xianyun.provider;

import com.xianyun.common.service.UserService;
import com.xianyun.rpc.RpcApplication;
import com.xianyun.rpc.config.RegistryConfig;
import com.xianyun.rpc.config.RpcConfig;
import com.xianyun.rpc.model.ServiceMetaInfo;
import com.xianyun.rpc.registry.LocalRegistry;
import com.xianyun.rpc.registry.Registry;
import com.xianyun.rpc.registry.RegistryFactory;
import com.xianyun.rpc.server.HttpServer;
import com.xianyun.rpc.server.impl.VertxHttpServer;

/**
 * @author xianYun
 * @version 1.0
 **/
public class ProvideExample {
    public static void main(String[] args) {
        // RPC 框架初始化
        RpcApplication.init();

        // 注册服务
        String serviceName = UserService.class.getName();
        LocalRegistry.register(serviceName, UserServiceImpl.class);

        // 注册服务到注册中心
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
        serviceMetaInfo.setServiceName(serviceName);
        serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
        serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
        try {
            registry.register(serviceMetaInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 启动 web 服务
        try {
            HttpServer httpServer = new VertxHttpServer();
            System.out.println("Vert 端口号为：" + RpcApplication.getRpcConfig().getServerPort());
            httpServer.doStart(RpcApplication.getRpcConfig().getServerPort());
            System.out.println("========> RPC 服务启动成功");
        } catch (Exception e) {
            System.out.println("========> RPC 服务启动失败");
            throw new RuntimeException(e);
        }
    }
}
